<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="产品名称" prop="productId">
        <ErpSelectRemoteProduct
          v-model="formData.productId"
          @select="(product) => onChangeProduct(product)"
          placeholder="请选择产品"
        />
      </el-form-item>
      <el-form-item label="产品编码" prop="productBarCode">
        <el-input v-model="formData.productBarCode" placeholder="产品编码" disabled/>
        <!--        <ErpSelectRemoteProduct v-model="formData.productBarCode" @select="selectproductBarCode" style="width: 100%"/>-->
      </el-form-item>

      <el-form-item label="商品属性" prop="property">
        <el-input v-model="formData.property" placeholder="请输入商品属性" disabled/>
      </el-form-item>
      <!--      <el-form-item label="产品分类编号" prop="categoryId">-->
      <!--        <el-input v-model="formData.categoryId" placeholder="请输入产品分类编号"/>-->
      <!--      </el-form-item>-->
      <el-form-item label="单位" prop="unitId" disabled="">
        <ErpSelectUnit v-model="formData.unitId" disabled/>
      </el-form-item>

      <el-form-item label="数量" prop="count">
        <el-input v-model="formData.count" placeholder="请输入数量"/>
      </el-form-item>
      <el-form-item label="成本价" prop="costPrice">
        <el-input v-model="formData.costPrice" disabled/>
      </el-form-item>
      <el-form-item label="费用" prop="cost">
        <el-input v-model="formData.cost" placeholder="请输入费用" disabled/>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number min="0" v-model="formData.sort" placeholder="请输入排序"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入产品备注"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import ErpSelectRemoteProduct from '@/views/erp/product/product/components/ErpSelectRemoteProduct.vue'
import {ProductApi} from '@/api/erp/product/product'
import ErpSelectUnit from "@/views/erp/product/unit/components/ErpSelectUnit.vue";


const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  parentId: undefined,
  productName: undefined,
  productBarCode: undefined,
  categoryId: undefined,
  unitId: undefined,
  standard: undefined,
  remark: undefined,
  weight: undefined,
  costPrice: undefined,
  unit: undefined,
  cost: undefined,
  sort: undefined,
  property: undefined
})
const formRules = reactive({
  parentId: [{required: true, message: '父编码不能为空', trigger: 'blur'}],
  productName: [{required: true, message: '产品名称不能为空', trigger: 'blur'}],
  productBarCode: [{required: true, message: '产品商品编码不能为空', trigger: 'blur'}],
  count: [{required: true, message: '数量不能为空', trigger: 'blur'}],
  property: [{required: true, message: '商品属性不能为空', trigger: 'blur'}],
  unitId: [{required: true, message: '单位编号不能为空', trigger: 'blur'}],
  unit: [{required: true, message: '数量不能为空', trigger: 'blur'}],
  // costPrice: [{required: true, message: '成本价不能为空', trigger: 'blur'}],
  // cost: [{required: true, message: '费用不能为空', trigger: 'blur'}],

})
const formRef = ref() // 表单 Ref
const parentId = ref()
/** 打开弹窗 */
const open = async (type: string, id?: number, parent?: Long) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  parentId.value = parent as any
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProductApi.getProductBomMaterial(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  formData.value.parentId = parentId.value
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ProductBomMaterial
    if (formType.value === 'create') {
      await ProductApi.createProductBomMaterial(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProductApi.updateProductBomMaterial(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    parentId: undefined,
    productName: undefined,
    productBarCode: undefined,
    categoryId: undefined,
    unitId: undefined,
    standard: undefined,
    remark: undefined,
    weight: undefined,
    costPrice: undefined,
    unit: undefined,
    cost: undefined,
    sort: undefined,
    property: undefined
  }
  formRef.value?.resetFields()
}

/** 处理产品变更 */
const onChangeProduct = (product) => {
  if (product) {
    console.log(product)
    formData.value.productBarCode = product.barCode
    formData.value.productName = product.name
    formData.value.categoryId = product.categoryId
    formData.value.unitId = product.unitId
    formData.value.property = product.property
    formData.value.costPrice = product.purchasePrice
  }
}


// 3. 核心：监听子组件事件，接收完整商品数据
const selectproductBarCode = (product) => {
  if (product) {
    formData.value.productName = product.name
    formData.value.categoryId = product.categoryId
    formData.value.unitId = product.unitId
    formData.value.property = product.property
    formData.value.costPrice = product.purchasePrice
  }
};


// 也可以使用watch监听变化（两种方式选一种即可）
watch(
  () => [formData.value.costPrice, formData.value.count],
  () => {
    const price = Number(formData.value.costPrice) || 0;
    const quantity = Number(formData.value.count) || 0;
    // 计算并保留两位小数
    formData.value.cost = (price * quantity).toFixed(6);
  },
  {immediate: false} // 初始化时立即计算
);
</script>
